"""
图片服务模块
处理图片上传和解析
"""

import os
import uuid
from werkzeug.utils import secure_filename
import logging

# 尝试导入PIL模块
try:
    from PIL import Image
except ImportError:
    logging.error("PIL模块导入失败，请确保已安装Pillow包")
    raise ImportError("请先安装Pillow包: pip install Pillow")

try:
    import pytesseract
except ImportError:
    logging.error("pytesseract模块导入失败，请确保已安装pytesseract包")
    raise ImportError("请先安装pytesseract包: pip install pytesseract")

# 设置Tesseract路径
if os.name == 'nt':  # Windows系统
    pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'

class ImageService:
    def __init__(self, upload_folder='uploads'):
        """
        初始化图片服务
        :param upload_folder: 上传文件夹路径
        """
        self.upload_folder = upload_folder
        self.allowed_extensions = {'png', 'jpg', 'jpeg', 'gif'}
        
        # 确保上传目录存在
        os.makedirs(upload_folder, exist_ok=True)
        
    def process_image(self, file):
        """
        处理上传的图片
        :param file: 上传的文件对象
        :return: 处理结果字典
        """
        try:
            if not file:
                return {
                    "success": False,
                    "message": "未找到上传的文件"
                }
                
            if not self._allowed_file(file.filename):
                return {
                    "success": False,
                    "message": "不支持的文件类型"
                }
                
            # 生成安全的文件名
            filename = secure_filename(file.filename)
            # 添加UUID前缀避免文件名冲突
            unique_filename = f"{uuid.uuid4()}_{filename}"
            filepath = os.path.join(self.upload_folder, unique_filename)
            
            # 保存文件
            file.save(filepath)
            
            # 解析图片内容
            content = self._extract_image_content(filepath)
            
            return {
                "success": True,
                "message": "图片处理成功",
                "filename": unique_filename,
                "content": content,
                "url": f"/uploads/{unique_filename}"
            }
            
        except Exception as e:
            logging.error(f"处理图片时发生错误: {str(e)}")
            return {
                "success": False,
                "message": f"处理图片时发生错误: {str(e)}"
            }
            
    def _allowed_file(self, filename):
        """
        检查文件类型是否允许
        :param filename: 文件名
        :return: 是否允许
        """
        return '.' in filename and \
               filename.rsplit('.', 1)[1].lower() in self.allowed_extensions
               
    def _extract_image_content(self, filepath):
        """
        从图片中提取内容
        :param filepath: 图片文件路径
        :return: 提取的内容
        """
        try:
            # 打开图片
            image = Image.open(filepath)
            
            # 使用OCR提取文字
            text = pytesseract.image_to_string(image, lang='chi_sim+eng')
            
            return text.strip()
            
        except Exception as e:
            logging.error(f"提取图片内容时发生错误: {str(e)}")
            return "无法提取图片内容" 